package corelayer.packets;

import corelayer.IMessage;
import corelayer.INode;
import corelayer.IPacket;
import corelayer.IPacketFactory;
import corelayer.Message;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * メッセージを伝達するパケットです
 */
public class MessagesPacket implements IPacket {

    private Collection<IMessage> messages;

    public MessagesPacket(Collection<IMessage> messages) {
        this.messages = messages;
    }

    @Override
    public void packTo(DataOutput out) throws IOException {
        for (IMessage msg : this.messages) {
            msg.writeTo(out);
        }
    }

    @Override
    public void onArrivedAt(INode node) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public static class Factory implements IPacketFactory {

        @Override
        public IPacket unpack(DataInput data) throws IOException {
            Collection<IMessage> contents = new ArrayList<IMessage>();
            while(true){
                try{
                    IMessage msg = Message.decode(data);
                    contents.add(msg);
                }catch(IOException e){
                    break;
                }
            }
            return new MessagesPacket(contents);
        }
    }
}
